<?php
namespace app\api\controller\goods;

use app\common\controller\Api;

class GoodsCategory extends Api
{
    protected $noNeedLogin = ['goodsCategory','search'];
    protected $noNeedRight = ['*'];


    /**
     * 分类页面
     * @path api/Goods_category/GoodsCategory/goodsCategory
     */
    public function goodsCategory()
    {
        $page = $this->request->param('page',1);
        $name = $this->request->param('name','');
        $storeId = $this->auth->store_id;
        $userId = $this->auth->id;
        $category1 = $this->request->param('category1');
        $category2 = $this->request->param('category2');
        $minPrice = $this->request->param('min_price',0);
        $maxPrice = $this->request->param('max_price',99999);
        $sort = $this->request->param('sort', 'comprehensive'); // 默认综合排序
        $order = $this->request->param('order', 'DESC'); // 默认为降序
        $user = db('user')->where('id',$userId)->find();
        $notGoods = db('store')->where('id',$storeId)->value('not_goods');

        $whereHaving = "";
        $orderS = "";
        $where = [];
        $whereIn = [];
        $ids = [];
        if (!empty($notGoods)) {
            $ids = explode(',',trim($notGoods));
            $whereIn['id'] = ['not in',$ids];
        }

        if (!empty($category1)) {
            $where['cate_id'] = $category1;

        }
        if (!empty($category2)) {
            $where['cate_id2'] = $category2;
        }

        $where['is_on_sale'] = 1;

        $cateGoryList = db('goodscate')->where([
            'pid'=>0,
            'status'=>1,
        ])->order('weigh DESC')->select();
        foreach ($cateGoryList AS $key => $value) {
            $children = db('goodscate')->where([
                'pid'=>$value['id'],
                'status'=>1
            ])->order('weigh DESC')->select();
            $cateGoryList[$key]['children'] = $children;
        }


        if (!empty($name)) {
            $where['goods_name'] = ['like',"%".$name.'%'];
        }

        // 价格筛选
        $selectField = "price";
        if ($user['type'] == 2) {
            //高级用户
            $selectField = "ROUND(highuser_discount/100*price,2)";//
        } elseif ($user['type'] == 3) {
            //合伙人
            $selectField = "ROUND(partner_discount/100*price,2)";//
        }

        // 价格筛选
        $minPrice = $minPrice ? $minPrice : 0;
        $maxPrice = $maxPrice ? $maxPrice : 999999;
        if ($minPrice > $maxPrice) {
            $this->error('最小金额不能高于最大金额');
        }
        if ($minPrice > 0 || $maxPrice < 999999) {
            $whereHaving = $selectField." BETWEEN '{$minPrice}' AND '{$maxPrice}'";
        }

        // 排序逻辑
        switch ($sort) {
            case 'collection_num':
                $orderS = "collection_num ".$order;
                break;
            case 'cashsale':
                $orderS = "(cashsale+salecount) ".$order;
                break;
            case 'price':
                $orderS = $selectField." ".$order;
                break;
            case 'comprehensive':
                // 综合排序：收藏量+销量+价格（这里假设先按收藏量，再按销量，最后按价格，均为降序）
                $orderS = 'collection_num DESC, cashsale DESC, price DESC';
                break;
            default:
                // 默认综合排序
                $orderS = 'collection_num DESC, cashsale DESC, price DESC';
        }

        //var_dump($where);die;
        $goods = db('goods')
            ->where($where)
            ->where($whereIn)
            ->where($whereHaving)
            ->orderRaw($orderS)
            ->paginate(10, false, ['page' => $page]);
        $goods = $goods->toArray();
        $goods['data'] = goodsPriceReset($goods['data'],$this->auth->type);
        $goods['data'] = addWebSiteUrl($goods['data'],['image','goods_images']);
        $backList = [
            'goods'=>$goods,
            'category_list'=>$cateGoryList
        ];
        $this->success('请求成功',$backList);
    }

}
